package com.bbzn.device.client.controller;

import com.bbzn.device.client.vo.req.ImgByteVO;
import com.bbzn.device.client.vo.req.VideoVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.constant.PageConstant;
import com.bbzn.device.client.constant.RedisConstant;
import com.bbzn.device.client.constant.VideoConstant;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dataobject.Video;
import com.bbzn.device.client.dto.video.VideoDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.CommonService;
import com.bbzn.device.client.service.SystemParamByCacheService;
import com.bbzn.device.client.service.VideoService;
import com.bbzn.device.client.utils.*;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/video")
@Slf4j
@Api(value = "video", tags = "视频管理")
@ApiSort(value = 1)// 大分类顺序
//@CrossOrigin
public class VideoController extends BaseApiService {

    @Autowired
    private VideoService videoService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;


    @Autowired
    private OSSUtil ossClientUtil;


    /**
     * 生成带签名的视频截帧URL
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUrlByVideo", method = RequestMethod.POST)
    @OperationAnnotation(content = "生成带签名的视频截帧URL")
    public String getUrlByVideo(String url) throws Exception {
        OSSUtil ossUtil = new OSSUtil();
        String myUrl = ossUtil.getUrlByFast("https://babaznkj.oss-cn-shenzhen.aliyuncs.com/android_video/202006021431hssnj.mp4");
        System.out.println(myUrl);
        return myUrl;
    }

    /**
     * 返回视频列表数据(web)(获取视频+视频封面)
     * 根据视频标题和作者查询
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getVideoList", method = RequestMethod.POST)
    @OperationAnnotation(content = "返回视频列表数据(web)")
    public BaseResponse getVideoList(@RequestBody VideoVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(userId).isPresent()) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(reqVO.getPageSize()).isPresent()) {
            reqVO.setPageSize(PageConstant.PAGE_SIZE_APP);
        }
        if (!OptionalBean.ofNullable(reqVO.getPageNum()).isPresent()) {
            reqVO.setPageNum(PageConstant.PAGE_NUM);
        }
        VideoDTO videoDTO = new VideoDTO();//BabaBeanUtils.voToDto(reqVO, VideoDTO.class);
        if (null != reqVO.getPageNum()) {
            videoDTO.setPageNum(reqVO.getPageNum());
        }
        if (null != reqVO.getPageSize()) {
            videoDTO.setPageSize(reqVO.getPageSize());
        }
        // 模糊查詢
        if (OptionalBean.ofNullable(reqVO.getApprovalStatus()).isPresent()) {
            videoDTO.setApprovalStatus(reqVO.getApprovalStatus());
        }
        if (OptionalBean.ofNullable(reqVO.getVideoTitle()).isPresent()) {
            videoDTO.setVideoTitle(reqVO.getVideoTitle());
        }
        if (OptionalBean.ofNullable(reqVO.getUserPhone()).isPresent()) {
            videoDTO.setUserPhone(reqVO.getUserPhone());
        }
        videoDTO.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());

        PageInfo<VideoDTO> videoList = videoService.selectPageSelective(videoDTO);
        return setResultSuccess(videoList);
    }

    /**
     * 查询视频审批结果详情
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getAuditVideo", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询视频审批结果详情")
    public BaseResponse getAuditVideo(@RequestBody VideoVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(userId).isPresent()) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Map<String, Object> data = new HashMap();
        if (!OptionalBean.ofNullable(reqVO.getVideoId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoConstant.VIDEO_ENUM, VideoConstant.VIDEO_NO_VIDEOID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Video video = videoService.selectByPrimaryKey(reqVO.getVideoId());
        data.put("video", video);
        return setResultSuccess(data);
    }

    /**
     * 审核视频
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/auditVideo", method = RequestMethod.POST)
    @OperationAnnotation(content = "审核视频")
    public BaseResponse auditVideo(@RequestBody VideoVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(userId).isPresent()) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getVideoId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoConstant.VIDEO_ENUM, VideoConstant.VIDEO_NO_VIDEOID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getApprovalStatus()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(VideoConstant.VIDEO_ENUM, VideoConstant.VIDEO_NO_STATUS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getRejectReason()).isPresent() && reqVO.getApprovalStatus() == 2) {
            systemParam = systemParamByCacheService.getValues(VideoConstant.VIDEO_ENUM, VideoConstant.VIDEO_NO_REJECT_REASON_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        //User user = userClient.selectByPrimaryKey(userId);
        Video video = videoService.selectByPrimaryKey(reqVO.getVideoId());
        video.setApprovalStatus(reqVO.getApprovalStatus());
        video.setRejectReason(reqVO.getRejectReason());
        video.setUpdateTime(new Date());
        //记录审核人是谁
        video.setTntUserId(userId);
        video.setTntUserName(MayiktJwtUtils.getUsername(request, secretKey));
        videoService.updateByPrimaryKeySelective(video);

        systemParam = systemParamByCacheService.getValues(VideoConstant.VIDEO_ENUM, VideoConstant.VIDEO_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @OperationAnnotation(content = "上传图片")
    public Object uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("图片上传开始...");
        String destDir = "/upload/image";

    /* response.setHeader("Access-Control-Allow-Origin", "*");
     response.setHeader("Access-Control-Allow-Methods", "POST");*/
        ServletInputStream inputStream = request.getInputStream();

        //获取文件上传的真实路径
        String uploadPath = request.getSession().getServletContext().getRealPath("/");
        //保存文件的路径
        String filepath = destDir + File.separator + createNewDir();
        File destfile = new File(uploadPath + filepath);
        if (!destfile.exists()) {
            destfile.mkdirs();
        }
        //文件新名称
        String fileNameNew = getFileNameNew() + ".png";
        File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
        if (!f.exists()) {
            OutputStream os = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(os);

            byte[] buf = new byte[1024];
            int length;
            length = inputStream.read(buf, 0, buf.length);

            while (length != -1) {
                bos.write(buf, 0, length);
                length = inputStream.read(buf);
            }
            bos.close();
            os.close();
            inputStream.close();
            String lastpath = filepath + File.separator + fileNameNew;
            System.out.println("返回图片路径：" + lastpath);
            return lastpath;
        }
        return false;
    }

    /**
     * 将接收的base64转换成图片保存
     *
     * @param imgByteVO base64数据
     * @return 成功返回图片保存路径，失败返回false
     */
    @RequestMapping(value = "/saveToImgByStr", method = RequestMethod.POST)
    @OperationAnnotation(content = "将接收的base64转换成图片保存")
    public Object saveToImgByStr(@RequestBody ImgByteVO imgByteVO, HttpServletRequest request, HttpServletResponse response) {
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST");
        String imgByte = imgByteVO.getImgByte();
        imgByte = imgByte.replaceAll("data:image/png;base64,", "");
        String replace = imgByte.replace(" ", "+");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(replace);
            for (int i = 0; i < imageByte.length; ++i) {
                if (imageByte[i] < 0) {// 调整异常数据
                    imageByte[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (imageByte.length > 0) {
            try {
                //文件新名称
                String fileNameNew = getFileNameNew() + ".png";
                // 将上面生成的图片格式字符串 imgStr，还原成图片显示
                InputStream in = new ByteArrayInputStream(imageByte);
                String etag = ossClientUtil.uploadFile2OSS(in, fileNameNew);
                String fileUri = ossClientUtil.getImgUrl(etag);
                System.out.println("返回图片路径：" + fileUri);
                // TODO
                // 存放卡以及照片地址
                return fileUri;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            }
        }
        return false;
    }


    /**
     * 为文件重新命名，命名规则为当前系统时间毫秒数
     *
     * @return string
     */
    private static String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }

    /**
     * 以当前日期为名，创建新文件夹
     *
     * @return
     */
    private static String createNewDir() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        return fmt.format(new Date());
    }


}
